package com.rivercloud.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.view.JspView;

import com.alibaba.fastjson.JSONArray;
import com.rivercloud.dao.ExcelDAO;
import com.rivercloud.dao.ProjectDao;
import com.rivercloud.dao.RoleDao;
import com.rivercloud.dao.TableRowDao;
import com.rivercloud.dao.UserDao;
import com.rivercloud.dao.UserProjectDao;
import com.rivercloud.dao.UserRoleDao;
import com.rivercloud.dao.Impl.ProjectDaoImpl;
import com.rivercloud.dao.Impl.RoleDaoImpl;
import com.rivercloud.dao.Impl.TableRowDaoImpl;
import com.rivercloud.dao.Impl.UserDaoImpl;
import com.rivercloud.dao.Impl.UserProjectDaoImpl;
import com.rivercloud.dao.Impl.UserRoleDaoImpl;
import com.rivercloud.entity.Project;
import com.rivercloud.entity.Role;
import com.rivercloud.entity.TableRow;
import com.rivercloud.entity.User;
import com.rivercloud.entity.UserProject;
import com.rivercloud.entity.UserRole;
import com.rivercloud.entity.UserVo;
@Filters(@By(type=CheckSession.class, args={"user", "/login.jsp"}))   
@At("/project")
@Fail("http:500")
public class ProjectController {
	@Inject
	private ExcelDAO excelDAO = new ExcelDAO();
	private ProjectDao projectDao = new ProjectDaoImpl();
	private UserProjectDao userProjectDao = new UserProjectDaoImpl();
	private UserRoleDao userRoleDao = new UserRoleDaoImpl();
	private UserDao userDao = new UserDaoImpl();
	private RoleDao roleDao = new RoleDaoImpl();
	private TableRowDao tableRowDao = new TableRowDaoImpl();
	

	static SqlSessionFactory sqlSessionFactory = null;

	static {
		SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}

		sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
	}
	
	//检验项目名是否可用
	@At("/checkProjectName")
	public void checkProjectName(HttpServletRequest request,HttpServletResponse response) {
		try {
			String projectName = request.getParameter("projectName");
			Project existProject = projectDao.checkProjectName(projectName);
			if(existProject == null){
				response.getWriter().print("1");
			}else{
				response.getWriter().print("2");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}

	@At("/delete")
	@Ok("json")
	public Map deleteProject(HttpServletRequest request) {
		String tid = request.getParameter("projectId");
		
		Integer projectId = Integer.parseInt(tid);
		Map map = new HashMap();
		projectDao.deleteProject(projectId);
		
		map.put("true", true);
		return map;
	}
	
	@At("/deleteMember")
	
	public void deleteMember(HttpServletRequest request,HttpServletResponse response) {
		try {
			String tid = request.getParameter("projectId");
			String uid = request.getParameter("userId");
			
			Integer projectId = Integer.parseInt(tid);
			Integer userId = Integer.parseInt(uid);
		
			List<TableRow> tableRowList = tableRowDao.findTableRowByUserId(userId,projectId);
			
			if(tableRowList.size() == 0){
				userProjectDao.deleteMember(projectId,userId);
				Project project = projectDao.findProjectById(projectId);
				
				Integer member = project.getMemberNum()-1;
				
				projectDao.updateMemberNum(projectId,member);
				response.getWriter().print("1");
			}else{
				response.getWriter().print("2");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@At("/addMember")
	@Ok("json")
	public Map addMember(HttpServletRequest request) {
		try {
			String pid = request.getParameter("projectId");
			String memberName = request.getParameter("memberName");
			Integer projectId = Integer.parseInt(pid);
			Map map = new HashMap();
			
			//alan_18.2.28_start
			
			//List<UserProject> userProjects = new ArrayList<UserProject>();
			List<Integer> userIds = new ArrayList<Integer>();
			userIds = userProjectDao.findUserIdsByProjectId(projectId);
			
			int index=0;
			int user_num = userIds.size();  //通过projectid得到人数个数
			for(int i=0; i<user_num; i++)
			{
				if(userIds.get(i).equals(userDao.findIdByName(memberName))){
					//相同的话，不增加
					
				}else {
					//不同index加1
					index++;
				}
				
			}
			
			//都不相同，人数加1
			if(index==user_num){
				
			
			
			
			if (memberName != null && memberName != "") {
				UserProject userProject = new UserProject();
				int userId = userDao.findIdByName(memberName);
				userProject.setProjectId(projectId);
				userProject.setUserId(userId);
				userProject.setUserType(1);
				userProjectDao.addUserProject(userProject);
			}
			Project project = projectDao.findProjectById(projectId);
			
			Integer member = project.getMemberNum()+1;
		
			projectDao.updateMemberNum(projectId,member);
			map.put("true", true);
			return map;
			
			}
			//alan_18.2.28_end
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@At("/addProjectDesc")
	@Ok("json")
	public Map addProjectDesc(HttpServletRequest request) {
		try {
			String pid = request.getParameter("projectId");
			String projectDesc = request.getParameter("projectDesc");
			Integer projectId = Integer.parseInt(pid);
			Map map = new HashMap();
			
			Project project = projectDao.findProjectById(projectId);
			
			
			projectDao.addProjectDesc(projectId,projectDesc);
			map.put("true", true);
			return map;
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@At("/joinProjectList")
	@Ok("jsp:jsp.projects")
	public View joinProjectList(HttpServletRequest request) {
		
		try {
			int userId = Integer.parseInt(request.getParameter("userId"));
			
			List<Integer> list1 = userProjectDao.findProjectIdsByUserId(userId);
			
				List<Project> projects = projectDao.findProjectByIds(list1);
				if(projects.size() != 0){
				request.setAttribute("projects", projects);
				
			}else{
				return new JspView("jsp.notProjectMember");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	@At("/selectJoinProjectList")
	@Ok("json")
	public Object selectJoinProjectList(HttpServletRequest request) {
		
		try {
			int userId = Integer.parseInt(request.getParameter("userId"));
			
			List<Integer> list1 = userProjectDao.findProjectIdsByUserId(userId);
			
			List<Project> projects = projectDao.findProjectByIds(list1);
			
				Object json = JSONArray.toJSON(projects);
				return json;
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	@At("/selectJoinProject")
	@Ok("jsp:jsp.index")
	public void selectJoinProject(HttpServletRequest request) {
		
		try {
			int projectId = Integer.parseInt(request.getParameter("projectId"));
			Project project = projectDao.findProjectById(projectId);
			
			
			int userId = Integer.parseInt(request.getParameter("userId"));
			UserProject userProject = new UserProject();
			userProject.setProjectId(projectId);
			userProject.setUserId(userId);
			List<User> list = userDao.query_user_role_permission_all2(userProject);
			if(list.size()>0){
				User queryUser = list.get(0);
				UserVo userVo = new UserVo();
				userVo.setuId(queryUser.getId());
				userVo.setuName(queryUser.getName());
				List<Role> roles = queryUser.getRoles();
				Iterator<Role> iterator = roles.iterator();
				StringBuffer sb1 = new StringBuffer();
				StringBuffer sb2 = new StringBuffer();
				StringBuffer sb3 = new StringBuffer();
				while (iterator.hasNext()) {
					Role role = iterator.next();
					sb1.append(role.getId() + ",");
					sb2.append(role.getKeyword() + ",");
					sb3.append(role.getProjectId() + ",");
					/*List<Permission> permissions = role.getPermissions();
					Iterator<Permission> iterator2 = permissions.iterator();
					StringBuffer sbPid = new StringBuffer();
					StringBuffer sbKeyword = new StringBuffer();
					while (iterator2.hasNext()) {
						Permission permission = iterator2.next();
						sbPid.append(permission.getId() + ",");
						sbKeyword.append(permission.getKeyword() + ",");
					}
					sbPid.replace(sbPid.lastIndexOf(","), sbPid.lastIndexOf(",") + 1, "");
					sbKeyword.replace(sbKeyword.lastIndexOf(","), sbKeyword.lastIndexOf(",") + 1, "");
					userVo.setpId(sbPid.toString());
					userVo.setpKeyword(sbKeyword.toString());*/
				}
				sb1.replace(sb1.lastIndexOf(","), sb1.lastIndexOf(",") + 1, "");
				userVo.setrId(sb1.toString());
				sb2.replace(sb2.lastIndexOf(","), sb2.lastIndexOf(",") + 1, "");
				userVo.setrKeyword(sb2.toString());
				sb3.replace(sb3.lastIndexOf(","), sb3.lastIndexOf(",") + 1, "");
				userVo.setrProjectId(sb3.toString());
				request.getSession().setAttribute("userVo", userVo);
				System.out.println("userVo=" + userVo);
				
				request.getSession().setAttribute("project", project);
				
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	@At("/projectInfo")
	@Ok("jsp:jsp.projectInfo")
	public void projectInfo(HttpServletRequest request) {
		
		try {
			
			int projectId = Integer.parseInt(request.getParameter("projectId"));
			Project project = projectDao.findProjectById(projectId);
			List<Integer> list1 = userProjectDao.findUserIdsByProjectId(projectId);
			List<User> userList = userDao.findUserByIds(list1);
			int uId = userDao.findIdByName(project.getManagerName());
			User user1 = userDao.findUserById(uId);
			List<User> users = userDao.findAllUser();
			
			for (int i = 0; i < users.size(); i++) {
				
				if(users.get(i).getId() == user1.getId()){
					users.remove(i);
				}
			}
			/*User user = (User)request.getSession().getAttribute("user");
			int userId = user.getId();
			UserProject userProject = new UserProject();
			userProject.setProjectId(projectId);
			userProject.setUserId(userId);
			List<User> list = userDao.query_user_role_permission_all2(userProject);
			if(list.size()>0){
				User queryUser = list.get(0);
				UserVo userVo = new UserVo();
				userVo.setuId(queryUser.getId());
				userVo.setuName(queryUser.getName());
				List<Role> roles = queryUser.getRoles();
				Iterator<Role> iterator = roles.iterator();
				StringBuffer sb1 = new StringBuffer();
				StringBuffer sb2 = new StringBuffer();
				StringBuffer sb3 = new StringBuffer();
				while (iterator.hasNext()) {
					Role role = iterator.next();
					sb1.append(role.getId() + ",");
					sb2.append(role.getKeyword() + ",");
					sb3.append(role.getProjectId() + ",");
					List<Permission> permissions = role.getPermissions();
					Iterator<Permission> iterator2 = permissions.iterator();
					StringBuffer sbPid = new StringBuffer();
					StringBuffer sbKeyword = new StringBuffer();
					while (iterator2.hasNext()) {
						Permission permission = iterator2.next();
						sbPid.append(permission.getId() + ",");
						sbKeyword.append(permission.getKeyword() + ",");
					}
					sbPid.replace(sbPid.lastIndexOf(","), sbPid.lastIndexOf(",") + 1, "");
					sbKeyword.replace(sbKeyword.lastIndexOf(","), sbKeyword.lastIndexOf(",") + 1, "");
					userVo.setpId(sbPid.toString());
					userVo.setpKeyword(sbKeyword.toString());
				}
				sb1.replace(sb1.lastIndexOf(","), sb1.lastIndexOf(",") + 1, "");
				userVo.setrId(sb1.toString());
				sb2.replace(sb2.lastIndexOf(","), sb2.lastIndexOf(",") + 1, "");
				userVo.setrKeyword(sb2.toString());
				sb3.replace(sb3.lastIndexOf(","), sb3.lastIndexOf(",") + 1, "");
				userVo.setrProjectId(sb3.toString());
				request.getSession().setAttribute("userVo", userVo);
				System.out.println("userVo=" + userVo);
				request.getSession().setAttribute("project", project);
				}else{
				return new JspView("jsp.notProjectMember");
			}
				*/
				request.setAttribute("project", project);
				request.setAttribute("users", users);
				request.setAttribute("userList", userList);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	@At("/selectProject")
	@Ok("jsp:jsp.tableList")
	public void selectProject(HttpServletRequest request) {
		
		try {
			int projectId = Integer.parseInt(request.getParameter("projectId"));
		
			Project project = projectDao.findProjectById(projectId);
			
			request.getSession().setAttribute("project", project);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@At("/findFinishProjects")
	@Ok("jsp:jsp.finishProjects")
	public void findFinishProjects(HttpServletRequest request) {
		
		try {
			int userId = Integer.parseInt(request.getParameter("userId"));
			
			List<Integer> list1 = userProjectDao.findProjectIdsByUserId(userId);
			
			List<Project> allProjects = projectDao.findProjectByIds(list1);
			List<Project> projects = new ArrayList<Project>();
			for (Project project : allProjects) {
				if(project.getProjectStatus() == 1){
					projects.add(project);
				}
			}
			
			
			request.setAttribute("projects", projects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	@At("/findUnFinishProjects")
	@Ok("jsp:jsp.unFinishProjects")
	public void findUnFinishProjects(HttpServletRequest request) {
		
		try {
			
			int userId = Integer.parseInt(request.getParameter("userId"));
			
			List<Integer> list1 = userProjectDao.findProjectIdsByUserId(userId);
			
			List<Project> allProjects = projectDao.findProjectByIds(list1);
			List<Project> projects = new ArrayList<Project>();
			for (Project project : allProjects) {
				if(project.getProjectStatus() == 0 ){
					projects.add(project);
				}
			}
			
			
			request.setAttribute("projects", projects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	@At("/projectList")
	@Ok("jsp:jsp.projects")
	public void projectList(HttpServletRequest request) {

		try {
			int userId;
			if(request.getParameter("userId") != null ){
				userId = Integer.parseInt(request.getParameter("userId"));
				
			}else{
				User user  = (User) request.getSession().getAttribute("user");
				userId = user.getId();
			}
			
			List<Integer> list1 = userProjectDao.findProjectIdsByUserId(userId);
			
			List<Project> projects = projectDao.findProjectByIds(list1);
			
			

			request.setAttribute("projects", projects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	

	@At("/createProject")
	@Ok("redirect:/project/projectList")
	
	public void createProject(HttpServletRequest request) {
		try {
			Project project = new Project();
			String projectName = request.getParameter("projectName");
			String managerName = request.getParameter("managerName");
			Map<String, String[]> map = request.getParameterMap();
			System.out.println(map.size());
			int memberNum = map.size() - 2;
			project.setProjectName(projectName);
			project.setManagerName(managerName);
			project.setMemberNum(memberNum);
			projectDao.addProject(project);
			int projectId = projectDao.findIdByName(projectName);
			
			UserProject userProject1 = new UserProject();
			int userId1 = userDao.findIdByName(managerName);
			userProject1.setProjectId(projectId);
			userProject1.setUserId(userId1);
			userProjectDao.addUserProject(userProject1);
			
			roleDao.addManager(projectId);
			roleDao.addMember(projectId);
			Role role = roleDao.findManegerByPid(projectId);
			Role role2 = roleDao.findMemberByPid(projectId);
			UserRole userRole1 = new UserRole();
			
			userRole1.setUserId(userId1);
			userRole1.setRoleId(role.getId());
			userRoleDao.addUserRole(userRole1);
			 
			String s = request.getParameter("memberName1");
			
			
			for (int i = 1; i <= memberNum; i++) {

				String userName = request.getParameter("memberName" + i);
				if (userName != null && userName != "") {
					UserProject userProject = new UserProject();
					int userId = userDao.findIdByName(userName);
					userProject.setProjectId(projectId);
					userProject.setUserId(userId);
					userProject.setUserType(1);
					userProjectDao.addUserProject(userProject);
					
					UserRole userRole = new UserRole();
					
					userRole.setUserId(userId);
					userRole.setRoleId(role2.getId());
					userRoleDao.addUserRole(userRole);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
	@At("/create")
	@Ok("jsp:jsp.createProject")
	public void create(HttpServletRequest request) {
		try {
			List<User> users = userDao.findAllUser();
			request.setAttribute("users", users);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
